package com.ftw.commons.receiver

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import com.trello.rxlifecycle3.components.support.RxAppCompatActivity
import com.ftw.commons.BaseApplication
import com.ftw.commons.bean.NetworkChangeEvent
import org.greenrobot.eventbus.EventBus

/**
 * 描    述： 监听网络变化
 * 作    者：fantianwen
 * 时    间：2020-02-25
 */

class NetWorkChangeReceiver : BroadcastReceiver() {

    @SuppressLint("MissingPermission")
    override fun onReceive(context: Context?, intent: Intent?) {

        val connectionManager =
            context!!.getSystemService(RxAppCompatActivity.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkInfo = connectionManager.activeNetworkInfo

        if (BaseApplication.instance.mCurrentActivityName == "MainActivity"
        ) {
            if (networkInfo != null && networkInfo.isAvailable) {
                EventBus.getDefault().post(NetworkChangeEvent(true, networkInfo.type))
            } else {
                EventBus.getDefault().post(NetworkChangeEvent(false, -1))
            }
        }

    }

}
